import juice from "juice";
import {ElMessage} from 'element-plus';

export function solveWeChatMath() {
	const layout = document.getElementById('blueNote');
	const mjxs = layout.getElementsByTagName("mjx-container");
	for (let i = 0; i < mjxs.length; i++) {
		const mjx = mjxs[i];
		if (!mjx.hasAttribute("jax")) {
			break;
		}

		// mjx.removeAttribute("data");
		mjx.removeAttribute("jax");
		mjx.removeAttribute("display");
		mjx.removeAttribute("tabindex");
		mjx.removeAttribute("ctxtmenu_counter");
		const svg = mjx.firstChild;
		const width = svg.getAttribute("width");
		const height = svg.getAttribute("height");
		svg.removeAttribute("width");
		svg.removeAttribute("height");
		svg.style.width = width;
		svg.style.height = height;
	}
}

/**
 * 输出带有css样式的html代码
 * @returns {string} html
 * */
export function solveHtml() {
	const element = document.getElementById('blueNoteBox');
	let html = element.innerHTML;
	html = html.replace(/<mjx-container (class="inline.+?)<\/mjx-container>/g, "<span $1</span>");
	html = html.replace(/\s<span class="inline/g, '&nbsp;<span class="inline');
	html = html.replace(/svg><\/span>\s/g, "svg></span>&nbsp;");
	html = html.replace(/mjx-container/g, "section");
	html = html.replace(/class="mjx-solid"/g, 'fill="none" stroke-width="70"');
	html = html.replace(/<mjx-assistive-mml.+?<\/mjx-assistive-mml>/g, "");
	const markdownStyle = document.getElementById('markdownTheme')?.innerText;
	const codeStyle = document.getElementById('codeTheme')?.innerText;
	// const fontStyle = document.getElementById(FONT_THEME_ID).innerText;
	let res = "";
	try {
		res = juice.inlineContent(html, markdownStyle + codeStyle, {
			inlinePseudoElements: true,
			preserveImportant: true,
		});
	} catch (e) {
		ElMessage({
			message: "请检查 CSS 文件是否编写正确！",
			type: "error",
		})
	}

	return res;
}

/**
 * 复制内容到剪贴板
 * */
export function copyToClipboard(copyText) {
// 获取 input
	let input = document.getElementById("copy-input");
	if (!input) {
		// input 不能用 CSS 隐藏，必须在页面内存在。
		input = document.createElement("input");
		input.id = "copy-input";
		input.style.position = "absolute";
		input.style.left = "-1000px";
		input.style.zIndex = "-1000";
		document.body.appendChild(input);
	}
	// 让 input 选中一个字符，无所谓那个字符
	input.value = "NOTHING";
	input.setSelectionRange(0, 1);
	input.focus();

	// 复制触发
	document.addEventListener("copy", function copyCall(e) {
		e.preventDefault();
		e.clipboardData.setData("text/html", copyText);
		e.clipboardData.setData("text/plain", copyText);
		document.removeEventListener("copy", copyCall);
	});
	document.execCommand("copy");

	ElMessage({
		message: "复制成功！",
		type: "success",
	})
}
